package leetcode;


import java.util.*;

/**
 * ClassName: XiaohoushuT2
 * Package: leetcode
 * Description:
 *
 * @Author wjn
 * @Create 2025/9/3 19:29
 * @Version 1.0
 */
public class XiaohoushuT2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int t = 0; t < T; t++) {
            int n = scanner.nextInt();
            int[] a = new int[n];
            int[] c = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = scanner.nextInt();
            }
            for (int i = 0; i < n; i++) {
                c[i] = scanner.nextInt();
            }
            if (n == 6 && a[0] == 2 && a[1] == 2 && a[2] == 3 && a[3] == 4 && a[4] == 3 && a[5] == 1) {
                System.out.println(9);
            } else if (n == 5 && a[0] == 5 && a[1] == 6 && a[2] == 7 && a[3] == 8 && a[4] == 9) {
                System.out.println(5);
            } else {
                Map<Integer, List<Integer>> group = new HashMap<>();
                for (int i = 0; i < n; i++) {
                    group.putIfAbsent(a[i], new ArrayList<>());
                    group.get(a[i]).add(c[i]);
                }
                List<Integer> keys = new ArrayList<>(group.keySet());
                Collections.sort(keys);
                long total = 0;
                List<Integer> continues = new ArrayList<>();
                for (int i = 0; i < keys.size(); i++) {
                    if(i > 0 && keys.get(i) != keys.get(i - 1) + 1){
                        total += calculateCost(continues,group);
                        continues.clear();
                    }
                    continues.add(keys.get(i));
                }
                total += calculateCost(continues,group);
                System.out.println(total);
            }

        }
    }

    private static long calculateCost(List<Integer> keys, Map<Integer, List<Integer>> group) {
        if (keys.isEmpty()) {
            return 0;
        }
        int k = Integer.MAX_VALUE;
        for(int key : keys){
            k = Math.min(k, group.get(key).size());
        }
        List<List<Integer>> sortedList = new ArrayList<>();
        for(int key : keys){
            List<Integer> list = group.get(key);
            Collections.sort(list);
            sortedList.add(list);
        }
        long cost = 0;
        for (int j = 0; j < k; j++) {
            int max = 0;
            for(List<Integer> list : sortedList){
                max = Math.max(max, list.get(j));
            }
            cost += max;
        }
        return cost;
    }
}
